package photorganizer.common.transaction;

import java.lang.reflect.Method;

import photorganizer.common.bean.Interceptor;
import photorganizer.common.bean.Request;

public class TransactionInterceptor implements Interceptor {

	/* (non-Javadoc)
	 * @see photorganizer.common.bean.Interceptor#invoke(photorganizer.common.bean.Request)
	 */
	public Object invoke(Request request) throws Throwable {
		Method method = request.getMethod();

		if (TransactionHome.isActive() || !method.isAnnotationPresent(Transactional.class)) {
			return request.invoke();
		}

		boolean commit = false;
		TransactionHome.begin();
		try {
			Object result = request.invoke();
			commit = true;
			return result;
		}
		finally {
			if (commit) {
				TransactionHome.commit();
			}
			else {
				TransactionHome.rollback();
			}
		}
	}

}
